package io.geekidea.springbootplus.system.utils;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
 
public class HttpDownLoad {
	public static void download(String url, String body, HttpServletResponse response) {
		HttpURLConnection httpURLConnection = null;
		OutputStream out = null;
		InputStream inStream = null;
		try {
			URL sendUrl = new URL(url);
			httpURLConnection = (HttpURLConnection) sendUrl.openConnection();
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setRequestProperty("contentType", "application/json;charset=utf-8");
			httpURLConnection.setDoOutput(true); 
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setConnectTimeout(3000);
			httpURLConnection.setReadTimeout(3000);
			httpURLConnection.setRequestProperty(
					"User-agent",InetAddress.getLocalHost().getHostAddress() + ":"
							+ System.getProperty("catalina.home"));

			httpURLConnection.connect();

			out = httpURLConnection.getOutputStream();

			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));

			writer.write(body);
			writer.close();

			// 清空缓冲区数据
			out.flush();
			// 获取HTTP状态码
			int httpStatusCode = httpURLConnection.getResponseCode();
			if(httpStatusCode!=200){
				throw new RuntimeException("异常");
			}
			inStream = httpURLConnection.getInputStream();

			response.reset();

			response.setHeader("Content-Disposition", "attachment;fileName=test.jpg");

			response.setContentType("image/jpeg");

//			response.setContentType("application/force-download");
//			response.setContentType("multipart/form-data");
//         url = URLEncoder.encode(url,"UTF-8");
			try {
				OutputStream os = response.getOutputStream();

				byte[] buff = new byte[1024];
				int len = -1;
				while ((len = inStream.read(buff)) > 0) {
					os.write(buff, 0, len);
				}
				os.flush();
				os.close();

				inStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
	}
 
	//写文件
	private static void saveFileByByte(InputStream in, String path, int len)
			throws Exception {
		byte[] byteDatas = new byte[len];
		BufferedOutputStream bw = null;
		try {
			// 创建文件对象
			File f = new File(path);
			// 创建文件路径
			if (!f.getParentFile().exists())
				f.getParentFile().mkdirs();
			// 写入文件
			bw = new BufferedOutputStream(new FileOutputStream(path));
			int bytesRead = 0;
			while ((bytesRead = in.read(byteDatas, 0, byteDatas.length)) != -1) {
				bw.write(byteDatas, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				if (bw != null)
					bw.close();
			} catch (Exception e) {
				throw e;
			}
		}
	}
}